﻿#include "pathsettingwid.h"

#include "pathpiontwid.h"
#include "cfgjsonrw.h"
#include "paramadddialog.h"

PathSettingWid::PathSettingWid(QWidget* parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	setStyleSheet("font: 12pt \"Agency FB\"");
}

PathSettingWid::~PathSettingWid()
{}

void PathSettingWid::Init(const PathCfg& cfg)
{
	QStringList nas = cfg.name().split("-");
	if (nas.size() >= 2) {
		m_id = nas[1].toInt() + 1;

	} else {
		m_id = cfg.id();
	}
	ui.lineEdit->setText(cfg.name());
	ui.tabWidget->clear();
	for (auto& iter : cfg.points()) {
		auto temp = new PathPiontWid(this);
		temp->Init(iter);
		ui.tabWidget->addTab(temp, iter.name());
	}
}

PathCfg PathSettingWid::GetCfg()
{
	PathCfg cfg = {};
	cfg.id = m_id;
	cfg.name = ui.lineEdit->text();
	for (int i = 0; i < ui.tabWidget->count(); i++) {
		auto temp = qobject_cast<PathPiontWid*>(ui.tabWidget->widget(i));
		auto point = temp->GetCfg();
		point.pointId = i + m_id * 10;
		cfg.points().append(point);
	}
	return cfg;
}

void PathSettingWid::on_pushButton_add_fornt_clicked()
{
	ParamAddDialog dlg({ "路径点名称" }, this);
	dlg.exec();
	auto param = dlg.GetParam();
	if (param.size() != 1) {
		QMessageBox::warning(this, "ERROR", "路径点名称不能为空");
		return;
	}
	auto name = param.at(0);
	PathPointCfg cfg = {};
	cfg.name = name;
	cfg.mathType = 0;
	cfg.vel = 10;
	cfg.acc = 10;
	cfg.zone = 10;

	auto temp = new PathPiontWid();
	temp->Init(cfg);

	int index = ui.tabWidget->currentIndex();
	ui.tabWidget->insertTab(index, temp, name);

}

void PathSettingWid::on_pushButton_add_back_clicked()
{
	int index = ui.tabWidget->currentIndex();

	ParamAddDialog dlg({ "路径点名称" }, this);
	dlg.exec();
	auto param = dlg.GetParam();
	if (param.size() != 1) {
		QMessageBox::warning(this, "ERROR", "路径点名称不能为空");
		return;
	}
	auto name = param.at(0);
	PathPointCfg cfg = {};
	cfg.name = name;
	cfg.mathType = 0;
	cfg.vel = 10;
	cfg.acc = 10;
	cfg.zone = 10;

	auto temp = new PathPiontWid();
	temp->Init(cfg);


	ui.tabWidget->insertTab(index + 1, temp, name);
}

void PathSettingWid::on_tabWidget_tabCloseRequested(int index)
{
	auto ret = QMessageBox::question(this, "QUESTION", QString("确认删除%1, 删除后数据无法恢复").
		arg(ui.tabWidget->tabText(index)));
	if (ret == QMessageBox::StandardButton::Yes) {
		ui.tabWidget->widget(index)->deleteLater();
		ui.tabWidget->removeTab(index);
	}
}

